<?php

namespace app\common\model;

use app\common\exception\BusinessException;

class UserMaterial extends Base
{
    protected $createTime = 'a_time';
    protected $updateTime = 'u_time';


    /**
     * 设置资料有效期
     * @param $uid
     * @param $material_id
     * @param $expire
     * @throws
     */
    public function setExpire($uid, $material_id, $expire)
    {
        // 查询条件
        $where = [
            'uid' => $uid,
            'material_id' => $material_id,
        ];

        // 查询信息
        $info = $this->where($where)->find();

        // 根据课程存在是否设置有效期
        $time = time();
        if ($info) {
            $expire = $info['expire'] >= $time ? $info['expire'] + $expire : $time + $expire;
            $saveData = [
                'expire' => $expire,
            ];
            $isUpdate = $this->where($where)->save($saveData);
            if ($isUpdate === false) {
                throw new BusinessException('更新用户资料表失败');
            }
        } else {
            $expire = $time + $expire;
            $saveData = [
                'uid' => $uid,
                'material_id' => $material_id,
                'expire' => $expire,
                'a_time' => $time,
                'u_time' => $time,
            ];
            $isUpdate = $this->save($saveData);
            if ($isUpdate === false) {
                throw new BusinessException('新增用户资料表失败');
            }
        }
    }

    /**
     * getUserValidMaterial
     * @param $uid
     * @param $material_id
     * @return UserMaterial|array|mixed|\think\Model|null
     * @throws
     */
    public function getUserValidMaterial($uid, $material_id){
        // 查询条件
        $time = time();
        $where = [
            ['uid', '=', $uid],
            ['material_id', '=', $material_id],
            ['expire', '>', $time]
        ];

        // 查询数据
        return $this->where($where)->find();
    }

    /**
     * 查看是否拥有此资料
     * @param $uid
     * @param $material_id
     * @return bool
     */
    public function checkHasMaterial($uid, $material_id): bool
    {
        // 查询条件
        $time = time();
        $where = [
            ['uid', '=', $uid],
            ['material_id', '=', $material_id],
            ['expire', '>', $time]
        ];

        // 查询数据
        $count = $this->where($where)->count();
        if ($count) {
            return true;
        }
        return false;
    }
}